

var chat = {
	uid : "",
	chatu : null
};

chat.win = (function(){
	return {
		init : function(){
			var uindex = util.getQuery("u");
			chat.chatu = parent.window.chatmain.ulist[parseInt(uindex)];
			chat.uid = parent.window.parent.window.oschat.uid;
			
			if(chat.chatu!=null){
				im.api.initChatWs(chat.uid,chat.chatu.id);
				
				chat.win.viewInit();

				im.ws.onopen = function() { 
					console.info("ws access");
		        };

		        // 关闭WebSocket的回调
				im.ws.onclose = function() {
				};

				// 收到服务器发送的文本消息, event.data表示文本内容
				im.ws.onmessage = function(e) { 
					console.log(e.data);
					var msg = eval('(' + e.data + ')');
					var letter = msg.result;
					if(letter.from.id == chat.uid){
						chat.win.addMeMsg(msg);
					}else{
						chat.win.addOtherMsg(msg);
					}
					$('.chat-msg')[0].scrollTop = $('.chat-msg')[0].scrollHeight;
					parent.window.chatmain.win.addMsgCount(letter.from.id);
				};
			}
			
		},
		
		viewInit : function(){
			$('.chat-photo img').attr('src',chat.chatu.portrait );
			$('.chat-name').html(chat.chatu.name);
			var resume = chat.chatu.resume;
			$('.chat-resume').html(resume);
			
			chat.win.sendEventBind();
		},
		
		sendEventBind:function(){
			$('#send-btn').click(function(){
				var msg = $('#msg').val();
				if(msg!=null && msg!=''){
					var json = '{"t":1,"id":"0","m":"'+msg+'"}';
					im.ws.send(json);
					$('#msg').val('');
				}
			});
		},
		
		/**
		 * <div class="message-other">
						<div class="u-photo">
							<img width="35" height="35" src="http://static.oschina.net/uploads/user/89/179699_50.jpg">
						</div>
						<div class="msg-content">
							<div class="m-name">小猪</div>
							<div class="msg"><p>求种子！！！求种子！！！<br />求种子！！！求种子！！！</p></div>
						</div>
					</div>
		 */
		addOtherMsg :function(msg){
			var u = msg.result.from;
			var letter =  msg.result;
			var d = new Date();
			d.setTime(msg.time);
			var time = util.date2String(d,"HH:mm:ss");
			var html = '<div class="message-other">'
				+ '<div class="msg-content">'
				+ '<div class="msg"><p>'+letter.msg+' ('+time+') </p></div>'
				+ '</div></div>';
			$('.chat-msg').append(html);
		},
		
		/**
		 * <div class="message-me">
						<div class="msg-content-me">
							<div class="msg-me"><p>求种子！！！求种子！！！</p></div>
						</div>
					</div>
		 */
		addMeMsg :function(msg){
			var letter = msg.result;
			var html = '<div class="message-me"><div class="msg-content-me"><div class="msg-me"><p>'+letter.msg+'</p></div></div></div>'
			$('.chat-msg').append(html);
		}
	};
})();